/**
 * 聚合项目状态 生成柱子
 */
define([ "dojo/_base/declare", 
         "gistech/widgets/ClusterInfoWindow/InfoWindowWidgetBase",
         "dojo/_base/lang",
         "dojo/on",
         "dojo/query",
         "dojo/topic",
         "dojo/dom-style",
         "dojo/dom-class",
         "dojo/dom-construct",
         "dojo/text!./templates/TemplateCol.html",
         "gistech/lib/echarts.common.min","dijit/layout/ContentPane", "gistech/util/ajaxUtil",],//,"gistech/lib/echarts-plain",echarts "gistech/lib/echarts.common.min"
         
    function(declare,BaseWidget,lang,on,query,topic, style,domClass,domConstruct,
    		template,echars2,ContentPane,ajaxUtil) {
        return declare([BaseWidget], {
        	//模板页面
            templateString : template,
            clusterType:'landCount',
            constructor : function() {
            	this.inherited(arguments);
            	//
            	ioc.map.clusterDetailFlag=null; //点击统计信息标记 避免重复查询
            },
            
            //组件初始化方法
            postCreate : function() {
            	this.inherited(arguments);
            	this.addEvents();
            },

            //添加事件
            addEvents:function(){
            	topic.subscribe("initClusterTable", lang.hitch(this, this.createClusterTable));// 点击柱状图时 创建右侧表格
            	topic.subscribe("clusterDetailInfo", lang.hitch(this, this.clusterDetailData));//表格中区域地块类型详细信息
            },
            
          //人员完成度的查询
    		_memCompletePercentStatic:function(dimensionName,data,targets,cityTarget){
    			//debugger
    			this.memCompletePercentStatic={};
    			this.memCompletePercentStaticBarData={
					xAxisData:[],//, '获取'
					yAxisData:[],
					yAxisMaxValue:0,
					checkParamStandard:0,
					talkOverParamStandard:0,
  		 			tbodyTr:null
	  		 	};
    			for(var i=0;i<targets.length;i++){
    				this.memCompletePercentStaticBarData.xAxisData.push(targets[i].xmjd.substr(0,2));//'核查', '洽谈'
    			}
    			this._createEchartsBar(dimensionName,this.memCompletePercentStaticBarData);
    			this._getChartData(dimensionName,data,targets,cityTarget);
    			//生成图表
				this._setChartYAxisMaxValue();
				this._setChartOption();
				
    		},
    		_setChartYAxisMaxValue:function(){
    			var array=this.memCompletePercentStaticBarData.yAxisData.concat(new Array(this.memCompletePercentStaticBarData.checkParamStandard,this.memCompletePercentStaticBarData.talkOverParamStandard));
				this.memCompletePercentStaticBarData.yAxisMaxValue=Math.max.apply(Math,array);
    		},
    		_setChartOption:function(){
    			var cols = this.memCompletePercentStaticBarData.xAxisData;
    			var  option = {xAxis:[{data:cols}],
    					yAxis:[{max:this.memCompletePercentStaticBarData.yAxisMaxValue}],
    					series:[
    					        {data:this.memCompletePercentStaticBarData.yAxisData,
    						     markLine:{
    						    	 data:[]
    					           }}]};
    			for(var i=0;i<cols.length;i++){
    				 if(cols[i].indexOf("核查")>=0){
    					 option.series[0].markLine.data.push({
  		    	    	   name:'核查项目标准值',
  		    	    	   yAxis:this.memCompletePercentStaticBarData.checkParamStandard,
  		    	    	   lineStyle:{
  		    	    		   normal:{color:'#C1232B'}
  		    	           }
  		    	       });
          			 }else if(cols[i].indexOf("洽谈")>=0){
          				option.series[0].markLine.data.push({
			    	    	   name:'洽谈项目标准值',
			    	    	   yAxis:this.memCompletePercentStaticBarData.talkOverParamStandard,
			    	    	   lineStyle:{
			    	    		   normal:{color:'#B5C334'}
			    	           }
			    	       });
          			 }
    			}
    			this.memCompletePercentStaticChart.setOption(option);
    		},
    		_getChartData:function(dimensionName,data,targets,cityTarget){
    			var xAxis = targets.map(function(item){ return item.xmjd; });
//    			var targetValue =[];
            	cityTarget.forEach(lang.hitch(this, function(item){ 
             		 xAxis.forEach(lang.hitch(this, function(it){
             			 if(it.indexOf("核查")>=0){
             				this.memCompletePercentStaticBarData.checkParamStandard=item[it];
             			 }else if(it.indexOf("洽谈")>=0){
             				this.memCompletePercentStaticBarData.talkOverParamStandard=item[it];
             			 }
//             			 targetValue.push(item[it]);
             		 }));
             	}));
//            	this.memCompletePercentStaticBarData.checkParamStandard=targetValue[0];
//				this.memCompletePercentStaticBarData.talkOverParamStandard=targetValue[1];
            	
				this.memCompletePercentStaticBarData.yAxisData = xAxis.map(function(item){
            		return Number(data[item])||0;
            	});
    		},
    		//构造生成柱状图的格式数据
    		_createEchartsBar:function(dimensionName,object){
    			this.memCompletePercentStaticChart= echars2.init(this.stat2);
    			var option = {
    					backgroundColor: 'rgba(255,255,255,0.7)',//背景色
    					title:{
    						text:dimensionName
    					},
    		            tooltip : {
			                trigger: 'axis',
			                axisPointer : { //坐标轴指示器，坐标轴触发有效
			                    type:'shadow'//默认为直线，可选为：'line' | 'shadow'
			                },
			                formatter:"{b}:{c}"
    		            },
    		            grid: {
    		                left: '5%',
    		                right: '16%',
    		                bottom: '3%',
    		                containLabel: true
    		            },
    		            xAxis : [
    		                {
    		                   type : 'category',
    		                   data : object.xAxisData,
    		                   axisTick: {
    		                      alignWithLabel: true
    		                   }
    		                }
    		            ],
    		            yAxis : [
    		                {
    		                    type : 'value'
    		                }
    		            ],
    		            series : [
    		                {
    		                    name:'',
    		                    type:'bar',
    		                    itemStyle: {
    		                        normal: {
    		                            //好，这里就是重头戏了，定义一个list，然后根据所以取得不同的值，这样就实现了，
    		                            color: function(params) {
    		                                // build a color map as your need.
    		                                var colorList = ['#C1232B','#B5C334','#FCCE10'];
    		                                return colorList[params.dataIndex]
    		                            },
    		                            //以下为是否显示，显示位置和显示格式的设置了
    		                            label: {
    		                                show: true,
    		                                position: 'top',
    		                                formatter:function(obj){
    		                                    switch(obj.name){
    		                                        case "核查":
    		                                            var barValue = obj.value;
    		                                            var standardValue=this.memCompletePercentStaticChart.getOption().series[0].markLine.data[0].yAxis;
    		                                            var percent='完成度\n0%';
    		                                            if(standardValue != 0){
    		                                            	percent='完成度\n'+ (barValue/standardValue * 100).toFixed(0)+'%';
    		                                            }
    		                                            break;
    		                                        case "洽谈":
    		                                            var barValue = obj.value;
    		                                            var standardValue=this.memCompletePercentStaticChart.getOption().series[0].markLine.data[1].yAxis;;
    		                                            var percent='完成度\n0%';
    		                                            if(standardValue != 0){
    		                                            	percent='完成度\n'+ (barValue/standardValue * 100).toFixed(0)+'%';
    		                                            }
    		                                            break;
    		                                        /*case "获取":
    		                                            var percent='';
    		                                            break;*/
    		                                    }
    		                                    return percent;
    		                                }.bind(this)
    		                            }
    		                        }
    		                    },
    		                    barWidth: '30%',
    		                    data:object.yAxisData
    		                }
    		            ]
    		        };
    			
				this.memCompletePercentStaticChart.setOption(option);
    		},
            /**
             * 根据参数加载柱子
             */
            initChartPie:function(dimensionName,data,targets,cityTarget){
            	var xAxis = targets.map(function(item){ return item.xmjd; });
            	//var targetValue = targets.map(function(item){ return item.value; });
            	var targetValue =[];
            	cityTarget.forEach(function(item){ 
             		 xAxis.forEach(function(it){
             			 targetValue.push(item[it]);
             		 });
             	});
            	var result = xAxis.map(function(item){
            		return Number(data[item])||0;
            	});
            	var color=[];  
            	
            	option = {
            			tooltip : {
            		        trigger: 'axis'
            		    },
            		    toolbox: {
            		        show : true,
            		        feature : {
            		            mark : {show: true},
            		            dataView : {show: true, readOnly: false},
            		            magicType : {show: true, type: ['line', 'bar']},
            		            restore : {show: true}
            		        }
            		    },
            		    grid:{
            		    	x:100
            		    },
            		    calculable : true,
            		    xAxis : [
            		        {
            		            type : 'category',
            		            data : xAxis
            		        }
            		    ],
            		    yAxis : [
            		        {
            		            type : 'value'
            		        }
            		    ],
            		    series : [
            		        {
            		            name:'指标',
            		            type:'bar',
            		            data:targetValue,
            		            barMaxWidth:40
            		        },
            		        {
            		            name:'实际',
            		            type:'bar',
            		            data:result,
            		            barMaxWidth:40
            		        }
            		    ]
            		};
            		     
            	
            	var chart = echars2.init(this.stat2);
            	chart.setOption(option);
            	
            	on(chart,'click',lang.hitch(this,function (REG,params) {
            		var  cityDistName = REG;
            		ioc.map.clusterClickName = REG;
            		ioc.map.clusterDetailFlag=null;
            		topic.publish('initClusterTable',cityDistName);
            	},dimensionName));
            },
            
            //详细信息
            clusterDetailData:function(args){
            	
            	if(args.clusterlandType == undefined){
            		return;
            	}
            	 
            	  var projTypeName = args.clusterlandType;
            	  
            	  var parameter= "dimension="+ioc.map.ClusterDimension;
            	  parameter += "&xmjd="+projTypeName;
            	  parameter += "&areaName="+ioc.map.clusterClickName;
//            	  parameter += "&tableName=sde.wytz_1";
            	  parameter += "&tableName="+mapinfoTemplate.LandFeatureLayer.tableName;
            	  
            	  parameter += "&starteDate="+ioc.map.clusterProjectStartDate  ;
            	  parameter += "&endDate="+ioc.map.clusterProjectEndDate ;
            	  //
            	  if(ioc.map.clusterDetailFlag==null){
            		  ioc.map.clusterDetailFlag = parameter;
            	  }else if(ioc.map.clusterDetailFlag == parameter){
            		  return;
            	  }else{
            		  ioc.map.clusterDetailFlag = parameter;
            	  }
            	  
	       			 //后台处理数据
	       	      	ajaxUtil.request("../client/service/clusterController/clusterProjTypesDetailData",
	       	      		parameter,lang.hitch(this,function(result){
	       	      		 //debugger;
	       	    			 var Store = eval(result.result);
	       	    			 if(Store!=null && Store.length>0){
		       	      			var tableParam={
		       	    					"tableData":Store,
		       	    					"columnsData":this._tableDetailColumnsData(projTypeName),
		       	    					"sortName":'CSMC',
	//	       	    					"sortOrder":'asc'
		       	    				};
		       	    				var bootstrapTableParamSetting={};
		       	    				var tableTitle="项目进度详细信息列表";
		       	    				this._createTable(tableParam,bootstrapTableParamSetting,tableTitle);
	       	    			 }
	       	    	    })
	       	    	 )
            	

//            	    this._createTable(args);
            },
            
            _createTable:function(tableParam,bootstrapTableParamSetting,tableTitle){
            	require(["gistech/widgets/QueryTableList/QueryTableList"],lang.hitch(this,function(QueryTableList){
            		//debugger
    				var queryTableList = new QueryTableList(tableParam);
            		queryTableList.$table.bootstrapTable('refreshOptions',bootstrapTableParamSetting);
    				queryTableList.startup();
    				if($(Global.widgets.right.domNode).children(".queryList").length!=0){
    					$(Global.widgets.right.domNode).children(".queryList").remove();
    				}
    				//为table添加标题信息--定制化
    				$('.fixed-table-toolbar',queryTableList.domNode).css({"height":"42px","background-color":"#f5f5f5","margin-bottom":"5px","padding-top":"10px","border-radius": "4px","margin-top": "6px"});
    				var headHTML='<span style="font-size: 16px;padding-left: 10px;">'+tableTitle+'</span>';
    				domConstruct.place(headHTML, $('.fixed-table-toolbar',queryTableList.domNode)[0], "first");
    				$('.fixed-table-toolbar .columns',queryTableList.domNode).css({"margin-top":"-5px","margin-right":"10px"});
    				$('.fixed-table-toolbar .search',queryTableList.domNode).css({"margin-top":"-28px","margin-left": "158px"});
    				var panel = new ContentPane();
    				$(panel.domNode).wrapInner(queryTableList.domNode);
    				if($('.centerPanel>.dijitContentPane>:nth-child(2)',Global.widgets.right.domNode).length == 1){
    					$('.centerPanel>.dijitContentPane>:nth-child(2)',Global.widgets.right.domNode).remove();
    				}
    				Global.widgets.right.addTab(panel);
    				
    				//当非管理员时不能使用导出Excel
    				if(!ioc.map.userInfoData.isManager){
    					document.getElementsByClassName("btn btn-default dropdown-toggle")[0].style.display='none';
    					document.getElementsByClassName("btn btn-default dropdown-toggle")[1].style.display='none';
    					$('.fixed-table-toolbar .search',queryTableList.domNode).css({"margin-top":"-28px","margin-left": "158px"});
    				}
    			}));
            },
            
    		//地块列数据
    		_bufferBlockColumsData:function(){
            	var arr=[
    			 {field:'CODE',title:'地块编号',width:30,align:'center'},
                 {field:'CSMC',title:'城市名称',width:40,align:'center'},
                 {field:'FQMC',title:'分区名称', width:30,align:'center'},
                 {field:'GYMJ',title:'用地面积',width:40,align:'center'},
                 {field:'JCFNF',title:'旧厂房年份',width:30,align:'center',visible:false},
                 {field:'GZLX',title:'改造类型', width:30,align:'center',visible:false},
                 {field:'NGZYT',title:'拟改造用途',width:30,align:'center',visible:false},
                 {field:'JHGZNF',title:'计划改造年份',width:40,align:'center',visible:false},
                 {field:'QSDWMC',title:'权属单位名称', width:30,align:'center',visible:false}
           		];
      			return arr;
    		},
    		
    		//地块数据对象
    		_bufferBlockDataObj :function(attr){
    			var obj={};
    			obj['CODE']=attr.CODE;
    			obj['CSMC']=attr.CSMC;
    			obj['FQMC']=attr.FQMC;
    			obj['GYMJ']=attr.GYMJ;
    			obj['JCFNF']=attr.JCFNF;
    			obj['GZLX']=attr.GZLX;
    			obj['NGZYT']=attr.NGZYT;
    			obj['JHGZNF']=attr.JHGZNF;
    			obj['QSDWMC']=attr.QSDWMC;
    			return obj;
    		},
          
            //进行表格数据的填充
            createClusterTable:function(cityDistName){
            	//debugger
            	//将右侧组件展开
    			if(!Global.widgets.right.hasExpand){
    				Global.widgets.right.expandLeft();
    			}
    			Global.widgets.right.removeAllTab();
            	//debugger
    			require(["gistech/widgets/QueryTableList/QueryTableList"],lang.hitch(this,function(QueryTableList){
    				//debugger
    				var queryTableList = new QueryTableList({
    					"tableData":this._tableData(cityDistName),
    					"columnsData":this._tableColumnsData(cityDistName),
    					"sortName":null,
    					"sortOrder":null
    				});
    				queryTableList.startup();
    				queryTableList.$table.bootstrapTable('refreshOptions',{detailView:false,search:false});
    				if($(Global.widgets.right.domNode).children(".queryList").length!=0){
    					$(Global.widgets.right.domNode).children(".queryList").remove();
    				}
    				$('.fixed-table-toolbar',queryTableList.domNode).css({"height":"42px","background-color":"#f5f5f5","margin-bottom":"5px","padding-top":"10px","border-radius": "4px","margin-top": "6px"});
    				var headHTML='<span style="font-size: 16px;padding-left: 10px;">聚合统计信息列表</span>';
    				domConstruct.place(headHTML, $('.fixed-table-toolbar',queryTableList.domNode)[0], "first");
    				$('.fixed-table-toolbar .columns',queryTableList.domNode).css({"margin-top":"-5px","margin-right":"10px"});
    				$('.fixed-table-container .pagination-detail',queryTableList.domNode).css("display","none");
    				var panel = new ContentPane();
    				$(panel.domNode).wrapInner(queryTableList.domNode);
    				Global.widgets.right.addTab(panel);
    			}));
            },
            
            _tableColumnsData:function(cityDistName){
            	var arr=[
        				 {field:'name',title:'('+cityDistName+')外业项目进度名称',width:30,align:'center'},
                         {field:'count',title:'项目数(个)',width:40,align:'center'}
        				 ];
            	 
      			return arr;
    		},
    		

    		
    		_tableData:function(cityDistName){
    			var arr = this.dealClusterData(cityDistName);
    			return arr;
    		},
    		
    		dealClusterData:function(cityDistName){
    			var result =[];
    			var feaset ; 
	      		if(ioc.map.ClusterDimension == 'city'){
	      			feaset = ioc.map.shifeatures ;
	    		}else if(ioc.map.ClusterDimension == 'distinct'){
	    			feaset = ioc.map.qufeatures ;
	    		}
    			for(var i=0;i<feaset.length;i++){
    				var fs = feaset[i];
    	        	var tPoint = fs.point;
    	        	var name = fs.name ; 
    	        	var clusdata = ioc.map.clusterData;
    	     		 if(clusdata.length>0){
    	     			 for(var j=0;j<clusdata.length;j++){
    	     				 var data = clusdata[j];
    	     				 var dimensionName = "";
    	     				 if(  ioc.map.ClusterDimension == 'distinct'){
    	     					dimensionName = data.REG
    	     				 }else if(  ioc.map.ClusterDimension == 'city'){
    	     					dimensionName = data.REG
    	     				 }else if(flag==3 || ioc.map.ClusterDimension == 'province' ){ 
    	     					dimensionName = ""; //TODO 省
    	     				 }
    	     				  
    	     				 if(cityDistName == dimensionName ){
    	     					 var isCity = false;
    	     					   if(ioc.map.ClusterDimension=='city' && data.district==undefined){
    	     							 isCity = true ; 
    	     					   }
    	     					   if( ioc.map.ClusterDimension=='city' && !isCity){break;};
    	     					   var result = this.toObj(data['核查项目'],data['洽谈项目'],data['获取项目']);
    	     					   return result;
    	     				 }
    	     			 }
    	     		 }
    			}
    		},
    		toObj: function(czldCount,gyjcydCount,sjjcCount){
                	var result=[];
                	 
                	if(czldCount!=undefined && czldCount != '' && czldCount != 0){
                		result.push({name:'核查项目',count:czldCount});
                	}
                	if(gyjcydCount!=undefined && gyjcydCount != '' && gyjcydCount != 0){
                		result.push({name:'洽谈项目',count:gyjcydCount});
                	}
                	if(sjjcCount!=undefined && sjjcCount != '' && sjjcCount != 0){
                		result.push({name:'获取项目',count:sjjcCount});
                	}
                	return result;
    		},
    		
            startup:function(dimensionName,data,targets,cityTarget){
            	this.inherited(arguments);
//            	this.initChartLine();
            	//this.initChartPie(dimensionName,data,targets,cityTarget);
            	this._memCompletePercentStatic(dimensionName,data,targets,cityTarget);
            },
            
            
    		//详细列表中的类
            _tableDetailColumnsData:function(landType){
            	
            	var arr = [];
            		arr = [
            		    {field:'OBJECTID',title:'OBJECTID',width:40,visible:false},
       					{field:'XMJD',title:'项目阶段',width:40},
       					{field:'DKBM',title:'城市地块编码',width:40,visible:false},
       					{field:'DKMC',title:'地块名称', width:40},
       					{field:'CS',title:'市', width:40,visible:false},
       					
       					{field:'QJ',title:'区', width:40 ,visible:false},
       					{field:'ZJ',title:'镇街', width:40 ,visible:false},
       					{field:'DZ',title:'地址', width:40  ,visible:false},
       					{field:'XMSX',title:'项目属性', width:60},
       					{field:'TZFS',title:'拓展方式', width:60},
       					
       					{field:'TGXX',title:'土规信息', width:60,visible:false},
       					{field:'KGXX',title:'控规信息', width:60,visible:false},
       					{field:'XZJSXX',title:'现状建设信息', width:60,visible:false},
       					{field:'ZYDMJ',title:'总用地面积', width:60,visible:false},
       					{field:'JYDMJ',title:'净用地面积', width:40,visible:false},
       					
       					{field:'DKRJL',title:'地块容积率', width:60,visible:false},
       					{field:'SYQXX',title:'所有权信息', width:60,visible:false},
       					{field:'QSDW',title:'权属单位', width:60,visible:false},
       					{field:'GHZH',title:'规划证号', width:60,visible:false},
       					{field:'GTZH',title:'国土证号', width:60,visible:false},
       					
       					{field:'LXRSX',title:'联系人属性', width:60,visible:false},
       					{field:'LXRXM',title:'联系人姓名', width:30,visible:false},
       					{field:'LXFS',title:'联系方式', width:30,visible:false},
       					{field:'BZJ',title:'保证金', width:30,visible:false}, 
       					{field:'ZDJ',title:'总地价', width:30,visible:false}, 
       					
       					{field:'DJRQ',title:'登记日期', width:60,visible:false},
       					{field:'DQGS',title:'地区公司', width:30,visible:false},
       					{field:'TZSYB',title:'拓展事业部', width:30,visible:false},
       					{field:'TZZ',title:'拓展组', width:30,visible:false}, 
       					{field:'YJQYSJ',title:'预计签约时间', width:30,visible:false}, 
       					
       					{field:'YJHQSJ',title:'预计获取时间', width:60,visible:false},
       					{field:'SJQYSJ',title:'实际签约时间', width:30,visible:false},
       					{field:'SJHQSJ',title:'实际获取时间', width:30,visible:false},
       					{field:'BZ',title:'备注', width:30,visible:false}, 
       					{field:'USERNAME',title:'用户名称', width:30,visible:false}
                   	    ];
             
     
      			return arr;
    		},
    		
    		
            
            destroy:function(){
            	this.inherited(arguments);
            }
        });
    });
